package hos.permission;

import android.content.Intent;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultCaller;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>Title: ActivityResultCompat </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2024-01-03 22:10
 */
public final class PermissionResultContracts {
    private PermissionResultContracts() {
    }

    public static ActivityResultLauncher<Intent> createResult(@NonNull ActivityResultCaller activityResultCaller, @NonNull ActivityResultCallback<ActivityResult> resultCallback) {
        return activityResultCaller.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), resultCallback);
    }

    public static ActivityResultLauncher<String[]> createMultiplePermission(@NonNull ActivityResultCaller activityResultCaller, @NonNull OnPermissionResultListener.onRefusedListener errorListener, @NonNull OnPermissionResultListener.onSuccessListener successListener) {
        return activityResultCaller.registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
            /** @noinspection ConstantValue*/
            @Override
            public void onActivityResult(Map<String, Boolean> map) {
                Set<String> keySet = map.keySet();
                List<String> errorPermissions = new ArrayList<>();
                for (String key : keySet) {
                    if (Boolean.FALSE.equals(map.get(key))) {
                        errorPermissions.add(key);
                    }
                }
                if (errorPermissions.isEmpty()) {
                    // 权限申请成功
                    if (successListener != null) {
                        successListener.onSuccess();
                    }
                    return;
                }
                // 权限申请失败
                if (errorListener != null) {
                    errorListener.onRefused(errorPermissions);
                }
            }
        });
    }

    public static ActivityResultLauncher<String> createPermission(@NonNull ActivityResultCaller activityResultCaller, @NonNull ActivityResultCallback<Boolean> resultCallback) {
        return activityResultCaller.registerForActivityResult(new ActivityResultContracts.RequestPermission(), resultCallback);
    }
}
